<template>
  <div
    class="map-div"
    :style="{ height: divHeight + 'px', width: divWidth}"
  >
    <div id="my-map">
    </div>

    <!-- 搜索框 -->
    <search-input
      ref="SearchInput"
      :localSearch="localSearch"
      :geocoder="geocoder"
      @getResults="handleResult"
      @clearMarkers="clearMarkers"
      @selectPoint="selectPoint"
      @handleGeocoder="handleGeocoder"
      @governmentResult="governmentResult"
    ></search-input>

    <!-- 工具栏 -->
    <!-- <tool-list ref="ToolList"></tool-list> -->
  </div>

</template>

<script>
import SearchInput from './search.vue';
import ToolList from './tool.vue';

export default {

  components: {
    SearchInput,
    ToolList
  },
  data () {
    return {
      divHeight: window.innerHeight - 70,
      divWidth: document.body.clientWidth,
      localSearch: null,
      map: null,
      geocoder: null,
      administrative: null
    }
  },
  methods: {
    mapInit () {
      var zoom = 12;
      // 图层对象
      var layer = new T.TileLayer('http://t0.tianditu.gov.cn/DataServer?T=img_w&x={x}&y={y}&l={z}&tk=9aa421bfac4b31f0ad91a7118973689d', { minZoom: 1, maxZoom: 18 });
      console.log('DataServer:', layer)

      // this.map.addLayer(layer);

      // https://t4.tianditu.gov.cn/img_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=img&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&tk=9aa421bfac4b31f0ad91a7118973689d&TILECOL={x}&TILEROW={y}&TILEMATRIX={z}
      var layer2 = new T.TileLayer('http://t0.tianditu.gov.cn/DataServer?T=cia_w&x={x}&y={y}&l={z}&tk=9aa421bfac4b31f0ad91a7118973689d', { minZoom: 1, maxZoom: 18 });
      console.log('DataServer:', layer2)

      // this.map.addLayer(layer2);

      var mapOptions = {
        'projection': 'EPSG:4326',   // 设置投影类型
        'minZoom': 1,
        'maxZoom': 18,
        // layers: [layer, layer2]
      }
      this.map = new T.Map('my-map', mapOptions);
      this.map.centerAndZoom(new T.LngLat(39.92361, 116.38094), zoom);
      // 创建缩放平移控件对象
      var control = new T.Control.Zoom();
      control.setPosition(T_ANCHOR_BOTTOM_RIGHT);
      //添加缩放平移控件
      this.map.addControl(control);

      // 搜索对象
      this.localSearch = new T.LocalSearch(this.map, {
        pageCapacity: 15 // 每页显示数量
      });

      // 地理编码对象
      this.geocoder = new T.Geocoder();

      var mapType_img = new T.MapType([layer, layer2], '卫星混合');
      console.log('自定义地图类型控件:', mapType_img.getLayers());
      //创建对象
      var ctrl = new T.Control.MapType({
        mapTypes: [
          // TODO:设置不生效
          {
            title: '卫星混合',
            icon: 'http://api.tianditu.gov.cn/v4.0/image/map/maptype/satellitepoi.png',
            layer: mapType_img
          }
        ]
      });
      console.log('地图控件:', ctrl)
      //添加地图类型控件
      this.map.addControl(ctrl);
      this.geoLocation();
    },
    computeHeight () {
      let that = this;
      window.onresize = () => {
        return (() => {
          that.divHeight = window.innerHeight - 70;
          that.divWidth = document.body.clientWidth;
        })();
      }

    },
    // 删除所有标注点以及对应标签
    clearMarkers () {
      var overlays = this.map.getOverlays();
      overlays.forEach(item => {
        if (item.id === 'marker') {
          this.map.removeOverLay(item);
        }
      })
    },
    handleResult (result) {
      console.log('获取检索结果', result);
      this.clearMarkers();
      // if (result && result.length > 0) {
      //   result.forEach(item => {
      //     //创建标注对象
      //     var marker = new T.Marker(new T.LngLat(item.lonlat.split(',')[0], item.lonlat.split(',')[1]));
      //     marker.id = 'marker';
      //     //向地图上添加标注
      //     this.map.addOverLay(marker);
      //     var label = new T.Label({
      //       text: "<b>" + item.name + "<b>",
      //       position: marker.getLngLat(),
      //       offset: new T.Point(3, -30)
      //     });
      //     label.id = 'marker';
      //     this.map.addOverLay(label);
      //   });
      // }
    },
    geoLocation () {
      var lo = new T.Geolocation();
      let that = this;
      var fn = function (e) {
        if (this.getStatus() == 0) {
          that.map.centerAndZoom(e.lnglat, 15)
          // alert("获取定位坐标："+e.lnglat.lat + "," + e.lnglat.lng)
          var marker = new T.Marker(e.lnglat);
          marker.id = 'marker';
          that.map.addOverLay(marker);

        }
        if (this.getStatus() == 1) {
          that.map.centerAndZoom(e.lnglat, e.level)
          // alert("获取定位坐标："+e.lnglat.lat + "," + e.lnglat.lng)
          var marker = new T.Marker(e.lnglat);
          marker.id = 'marker';
          that.map.addOverLay(marker);
          console.log('中心标注', marker)
        }
      }
      lo.getCurrentPosition(fn);
    },
    selectPoint (item) {
      var lnglat = new T.LngLat(item.lonlat.split(',')[0], item.lonlat.split(',')[1]);
      var marker = new T.Marker(lnglat);
      marker.id = 'marker';
      //向地图上添加标注
      this.map.addOverLay(marker);
      var label = new T.Label({
        text: "<b>" + item.name + "<b>",
        position: marker.getLngLat(),
        offset: new T.Point(3, -30)
      });
      label.id = 'marker';
      this.map.addOverLay(label);
      this.map.centerAndZoom(lnglat, 15)
    },
    handleGeocoder (val) {
      this.geocoder.getPoint(val, (result) => {
        console.log('地理编码返回结果', result)
        if (!result) {
          alert('没有相关数据');
        }
        if (result.getStatus() == 0) {
          this.map.panTo(result.getLocationPoint(), 16);
          //创建标注对象
          var marker = new T.Marker(result.getLocationPoint());
          //向地图上添加标注
          this.map.addOverLay(marker);
          var label = new T.Label({
            text: "<b>" + val + "<b>",
            position: marker.getLngLat(),
            offset: new T.Point(3, -30)
          });
          label.id = 'marker';
          this.map.addOverLay(label);
          this.map.centerAndZoom(result.getLocationPoint(), 15)
        } else {
          alert(result.getMsg());
        }
        this.$refs.SearchInput.setSearchDetail(result);
      })
    },
    // 行政区划事件
    governmentResult (result) {
      var lnglat;
      for (var i = 0; i < result.length; i++) {
        if (i === 0) {
          lnglat = new T.LngLat(result[0].lnt, result[0].lat);
          this.map.centerAndZoom(lnglat, 15)
          //创建标注对象
          var marker = new T.Marker(lnglat);
          //向地图上添加标注
          this.map.addOverLay(marker);
        }
        //         result[i].points = [{
        // "region":"116.236 40.117,116.234 40.107,116.236 40.106,116.238 40.105,116.238 40.104,116.239 40.104,116.239 40.104,116.24 40.104,116.25 40.103,116.25 40.103,116.251 40.103,116.252 40.104,116.253 40.104,116.253 40.104,116.253 40.105,116.253 40.105,116.253 40.106, "
        // }];
        if (result[i].points) {
          //绘制行政区划
          this.polygon(result[i].points);
        }

        // 绘制矩形
        var bounds = result[i].bound.split(',');
        var lnglatBound = new T.LngLatBounds(new T.LngLat(bounds[0], bounds[3]), new T.LngLat(bounds[2], bounds[1]));
        var rect = new T.Rectangle(lnglatBound, {
          color: "blue", weight: 0.5, opacity: 1, fillColor: "#CCF3FF", fillOpacity: 0.3
        });
        this.map.addOverLay(rect);
      }
    },
    // 绘制行政区划
    polygon (points) {
      var pointsArr = [];
      for (var i = 0; i < points.length; i++) {
        var regionLngLats = [];
        var regionArr = points[i].region.split(",");
        for (var m = 0; m < regionArr.length; m++) {
          var lnglatArr = regionArr[m].split(" ");
          var lnglat = new T.LngLat(lnglatArr[0], lnglatArr[1]);
          regionLngLats.push(lnglat);
          pointsArr.push(lnglat);
        }
        //创建面对象
        var polygon = new T.Polygon(regionLngLats, { color: "blue", weight: 1, opacity: 1, fillColor: "#CCF3FF", fillOpacity: 0.3 });
        //向地图上添加行政区划面
        this.map.addOverLay(polygon);
      }
      //显示最佳比例尺
      this.map.setViewport(pointsArr);
    }
  },

  mounted () {
    this.mapInit();
    this.computeHeight();
  },
  computed: {
    mapDivSize () {
      return {
        divHeight: this.divHeight,
        divWidth: this.divWidth
      }
    }
  },
  watch: {
    mapDivSize () {
      this.computeHeight();
    }
  }

}
</script>

<style lang="scss" scoped>
.map-div {
  position: relative;
}

#my-map {
  position: absolute;
  width: 100%;
  height: 100%;
}
</style>